package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
public class JWTUtil {

    /**
     * 获取加密token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,60*10*6);
        builder.withExpiresAt(calendar.getTime());
        return builder.sign(Algorithm.HMAC256("demo"));
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Map<String,String> analyzeToken(String token){
        Map<String,String> map=new HashMap<>();
        JWTVerifier demo = JWT.require(Algorithm.HMAC256("demo")).build();
        DecodedJWT verify = demo.verify(token);
        Map<String, Claim> claims = verify.getClaims();
        claims.forEach((k,v)->{
            map.put(k,v.asString());
        });
        return map;
    }


    /**
     * 根据request拿token并解析出用户名返回
     * @param request
     * @return
     */
    public static String getUsernameFromToken(HttpServletRequest request){
        String token = request.getHeader("token");
        JWTVerifier demo = JWT.require(Algorithm.HMAC256("demo")).build();
        DecodedJWT verify = demo.verify(token);
        Map<String, Claim> claims = verify.getClaims();
        String result="";
        for (String s : claims.keySet()) {
            if (s.equals("username")){
                result=claims.get(s).asString();
            }
        }
        return result;
    }
}
